<template>
  <div class="box">
    <PageTools show-before>
      <template #before>
        <span>共{{ total }}条记录</span>
      </template>
      <template #after>
        <el-button type="danger" size="small" @click="exportExcel">普通excel导出</el-button>
        <el-button type="info" size="small">复杂表头excel导出</el-button>
        <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
        <el-button type="primary" size="small" @click="addVisible=true">新增员工</el-button>
      </template>
    </PageTools>
    <el-card>
      <el-table border stripe :data="rows">
        <el-table-column label="序号" width="100px" align="center">
          <template #default="{$index}">
            {{ (params.page-1)*params.size+$index+1 }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" sortable prop="username" />
        <el-table-column label="头像" prop="staffPhoto">
          <template #default="{row}">
            <el-popover
              ref="popover"
              placement="right"
              width="200"
              trigger="click"
            >
              <img :src="ewmSrc" alt="">
            </el-popover>

            <img v-popover:popover v-imgerror="imgSrc" :src="row.staffPhoto" style="width:80%;" alt="" @click="showEwm(row.staffPhoto)">

          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" sortable />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="pyxs" />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry" width="150">
          <template #default="{row}">
            <span>{{ row.timeOfEntry | dateformat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template>
            <el-switch />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <!-- <template v-slot="scope">
          <template v-slot:default="scope">
          <template #default="scope">
          <template slot-scope="scope"> 老的写法 -->
          <template #default="{row}">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right;">
        <el-pagination
          :page-size="params.size"
          layout="total,sizes, prev, pager, next"
          :total="total"
          :page-sizes="sizes"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增对话框 -->
    <!-- sync是一个语法糖 -->
    <!-- <el-dialog title="新增员工" :visible="addVisible" width="40%" @update:visible="addVisible=$event"> -->
    <el-dialog title="新增员工" :visible.sync="addVisible" width="40%" @close="handleClose">
      <el-form ref="addForm" label-width="80px" :model="formData" :rules="rules">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" />
        </el-form-item>
        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker
            v-model="formData.timeOfEntry"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="formData.formOfEmployment">
            <el-option v-for="item in employees.hireType" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="formData.workNumber" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <el-input v-model="formData.departmentName" @focus="getDepartmentList" />
          <el-tree v-if="depts.length>0" :data="depts" default-expand-all :props="{label:'name'}" @node-click="handleNodeClick" />
        </el-form-item>
        <el-form-item label="转正时间" prop="correctionTime">
          <el-date-picker
            v-model="formData.correctionTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align:center;">
        <el-button type="primary" @click="add">确定</el-button>
        <el-button @click="addVisible=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 下面这个对话框组件只有在点击角色按钮的时候 showDialog的值才是true -->
    <!-- 这个时候才会创建才会执行created  -->
    <AssignRole v-if="showDialog" :id="id" :role-visible.sync="showDialog" />
    <!-- <AssignRole :role-visible="showDialog" @update:roleVisible="showDialog=$event" /> -->
  </div>
</template>

<script>
// 自定义指令 v-imgerror v-focus v-loading
// 过滤器 要的数据data中有，但是需要格式转换一下 一般货币 日期

// {{数据 | 过滤器名字}}

// Vue.filter('过滤器名',function(要处理的数据){
//   return 处理好的数据
// })
// [] -> true
// ￥$100
// 多利用提示 不要自己手写
// 按需引入都是有提示
import AssignRole from './components/assign-role.vue'
import { list2Tree } from '@/utils'
import { getDepartmentList } from '@/api/departments'
import employees from '@/api/constant/employees'
console.log(employees.hireType)
import { getEmployeeList, addEmployee } from '@/api/employees'
import QRCode from 'qrcode'
// import imgSrc from '@/assets/common/head.jpg'
export default {
  name: 'EmployeePage',
  components: {
    AssignRole
  },
  data() {
    return {
      params: {
        page: 1,
        size: 10
      },
      total: null,
      rows: [],
      // imgSrc:imgSrc
      imgSrc: require('@/assets/common/head.jpg'),
      addVisible: false,
      formData: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      rules: {
        username: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }, {
          min: 1, max: 4, message: '用户姓名为1-4位'
        }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '聘用形式不能为空', trigger: 'change' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        departmentName: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        timeOfEntry: [{ required: true, message: '入职时间', trigger: 'blur' }]
      },
      employees,
      depts: [],
      sizes: [5, 10, 20, 50],
      visible: false,
      ewmSrc: '',
      showDialog: false,
      id: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.params)
      this.rows = rows
      this.total = total
    },
    handleCurrentChange(current) {
      this.params.page = current
      this.getEmployeeList()
    },
    pyxs(row) {
      // find 找到这个对象
      // findIndex 找到这个对象 返回这个对象的索引值
      // return row.formOfEmployment
      const obj = employees.hireType.find(item => item.id === row.formOfEmployment)
      if (obj) {
        return obj.value
      } else {
        return '未知'
      }
    },
    async getDepartmentList() {
      const res = await getDepartmentList()
      this.depts = list2Tree(res.depts, '')
    },
    handleSizeChange(size) {
      this.params.size = size
      this.getEmployeeList()
    },
    handleNodeClick(node) {
      console.log(node)
      this.formData.departmentName = node.name
      this.depts = []
    },
    handleClose() {
      this.$refs.addForm.resetFields()
      this.depts = []
    },
    async add() {
      try {
        await this.$refs.addForm.validate()
        await addEmployee(this.formData)
        this.getEmployeeList()
        this.addVisible = false
      } catch (err) {
        console.log(err)
      }
    },
    async exportExcel() {
      const { rows } = await getEmployeeList({ page: 1, size: 999999 })
      const data = []
      const obj = {
        id: '',
        mobile: '',
        username: '',
        password: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        correctionTime: '',
        departmentName: '',
        staffPhoto: ''
      }
      rows.forEach(item => {
        data.push(Object.values({ ...obj, ...item }))
      })
      const tHeader = ['序号', '手机号', '姓名', '密码', '入职时间', '聘用形式', '工号', '转正时间', '部门', '头像']
      console.log(data)
      // vendor 是第三方但是也不是从npm或yarn下载下来的代码 不是我们写的但是网上npm也下不下来
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    async showEwm(src) {
      src = src === '' ? '图片不存在' : src
      try {
        console.log(await QRCode.toDataURL(src))
        // 颜色如果想生效，只能写十六进制的写法
        this.ewmSrc = await QRCode.toDataURL(src, { color: { dark: '#ff0000', light: 'blue' }})
        this.visible = true
      } catch (err) {
        console.error(err)
      }
    },
    showRole(id) {
      console.log(id)
      this.id = id
      this.showDialog = true
    }

  }
}
</script>

<style scoped lang='scss'>
.box{
  padding:20px;
}
</style>

